<template>
  <div class="carousel-config">
    <!-- 轮播图配置表单 -->
    <el-form :model="form" label-width="120px" style="margin-top: 20px;">
      <el-form-item label="上传图片">
        <el-upload
            class="avatar-uploader"
            :auto-upload = "false"
            :show-file-list="false"
            accept=".jpg,.png,.gif"
            :on-change="handleHeadIconChange"
        >
          <el-image v-if="courseImage" style="width: 256px; height: 144px" :key="imageKey" :src="courseImage"/>
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>

      <el-form-item label="轮播图顺序">
        <el-table :data="tableData" style="width: 100%" :key="tableKey">
          <el-table-column prop="fileUrl" label="图片" width="260">
            <template #default="{ row }">
              <img :src="row.fileUrl" alt="轮播图" style="width: 260px; height: 100px; object-fit: cover;" />
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button type="danger" @click="removeImage(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import {onMounted, ref} from "vue";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import carouselApi from "../../api/carousel.js";

let tableData = ref([]);
let courseImage = ref(null);


// Dom 挂载之后
onMounted(() => {
  getPictureList();
})

// 表单数据
const form = ref({});
//图像
const imageKey = ref(0);
const tableKey = ref(0);
//图像上传
const handleHeadIconChange =  async (uploadedFile) => {
  courseImage = uploadedFile.raw;
  if (courseImage) {
    const reader = new FileReader();
    reader.onload = async function () {
      courseImage = reader.result;//可以先在本地显示看看
      const res = await carouselApi.add({'fileUrl': courseImage});
      if (res.data.code === 200) {
        ElMessage.success("上传成功")
        await getPictureList();
      } else {
        ElMessage.error("上传失败")
      }
    };
    reader.readAsDataURL(courseImage);
  }
}

//获取图片列表
const getPictureList = async () => {
  const res = await carouselApi.list();
  tableData.value = res.data.data;
  tableKey.value ++;
}

// 删除图片
const removeImage = async (id) => {
  const res = await carouselApi.del({ 'id' : id });
  if (res.data.code === 200) {
    ElMessage.success("删除成功")
    await getPictureList();
  } else {
    ElMessage.error("删除失败")
  }
};

</script>

<style scoped>
.carousel-config {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}
</style>